// pages/operation-center/add-contract/index.js
const app = getApp()
const attachBaseUrl = app.globalData.attachBaseUrl
Page({
  data: {
    expand: false,
    showTypeSelector: false,
    currentType: 0,
    currentTypeName: '',
    maxDate: new Date(2040, 1, 1).getTime(),
    minDate: new Date(2020, 1, 1).getTime(),
    contractInfo: {
    },
    action: 'add',
    showTime: '',
    title: '添加合同',
    textareaHeight: 40, // 初始高度（单位：rpx）
    maxHeight: 200,     // 最大高度（单位：rpx）
    showScroll: false,  // 是否显示滚动条
    fileList: [],
    customerList: []
  },
  onLoad(option) {
    this.getCustomerList()
    if (option.id) {
      this.getContractInfo(option.id)
      this.setData({
        title: '编辑合同',
        action: 'edit'
      })
    }
  },
  getCustomerList() {
    app.axios('customer', {
      op: 'ajaxCustomerList'
    }).then(res => {
      if (res.code) {
        this.setData({
          customerList: res.lists
        })
      }
    })
  },
  getContractInfo(id) {
    app.axios('contract', {
      op: 'ajaxContractDetail',
      id: id
    }).then(res => {
      if (res.code) {
        const etime = res.item.etime
        this.setData({
          contractInfo: res.item,
          showTime: etime ? app.dateFormatter(etime) : ''
        })
        if (res.item && res.item.imgs && res.item.imgs.length > 0) {
          const imgList = []
          res.item.imgs.split(',').forEach((item, index) => {
            const img = {
              id: index,
              url: attachBaseUrl + item,
              isImage: true,
            }
            imgList.push(img)
          })
          this.setData({
            fileList: imgList,
          })
          console.log(this.data.fileList)
        }
      }
    })
  },
  navigateTo(e) {
    app.navigateTo(e.currentTarget.dataset.url, e.currentTarget.dataset.type)
  },
  toggleExpand() {
    this.setData({ expand: !this.data.expand })
  },
  toggleDateSelector() {
    const drawer = this.selectComponent('#v-drawer-date')
    drawer.toggleDrawer()
  },
  toggleCustomerSelector() {
    const picker = this.selectComponent('#list-picker')
    picker.togglePicker()
  },
  onDateConfirm(e) {
    this.toggleDateSelector()
    this.setData({
      'contractInfo.etime': app.dateFormatter(e.detail),
      showTime: app.dateFormatter(e.detail),
    })
  },
  handleInputChange(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    this.setData({
      [`contractInfo.${field}`]: value
    })
  },
  submit() {
    const parmas = this.data.contractInfo
    const tempList = []
    this.data.fileList.forEach(item => {
      tempList.push(item.url.replace(attachBaseUrl, ''))
    })
    parmas.imgs = tempList.toString()
    let op = 'ajaxContractUp'
    if (this.data.action === 'add') {
      op = 'ajaxContractAdd'
    }
    parmas.op = op
    console.log(parmas)
    app.axios(
      'contract',
      parmas
    ).then(res => {
      if (res.code) {
        wx.showToast({
          title: '修改成功'
        })
        setTimeout(() => {
          app.navigateTo('/pages/operation-center/index/index?activeTab=1', 'redirectTo')
        }, 1500);
      }
    })
  },
  handleTextareaChange(e) {
    const content = e.detail.value;
    const field = e.currentTarget.dataset.field
    // 计算行数
    const lineCount = content.split('\n').length;
    // 每行高度（根据实际行高调整，例如 40rpx/行）
    const lineHeight = 40;
    // 计算新高度
    let newHeight = lineCount * lineHeight;
    // 限制最大高度
    if (newHeight > this.data.maxHeight) {
      newHeight = this.data.maxHeight;
      this.setData({ showScroll: true });
    } else {
      this.setData({ showScroll: false });
    }
    // 更新高度
    this.setData({
      [`contractInfo.${field}`]: content,
      textareaHeight: newHeight
    })
  },
  handleChange(e) {
    if (e.detail.type === 'add') {
      // 处理新增文件
      const newFiles = e.detail.files;
      // 为新增文件生成唯一ID（防止编辑时索引冲突）
      const processedFiles = newFiles.map(file => ({
        ...file,
        id: file.id || `${Date.now()}-${Math.floor(Math.random() * 1000000)}`, // 唯一ID
      }));
      this.setData({
        fileList: [...this.data.fileList, ...processedFiles] // 合并文件列表
      });
      console.log(this.data.fileList)
    } else if (e.detail.type === 'remove') {
      // 处理删除文件
      const removedFile = e.detail.files; // 被删除的文件对象
      // 过滤掉被删除的文件
      const newFileList = this.data.fileList.filter(item => item.id !== removedFile.id);
      this.setData({
        fileList: newFileList
      });
    }
  },
  afterRead(event) {
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: 'https://example.weixin.qq.com/upload', // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: { user: 'test' },
      success(res) {
        // 上传完成需要更新 fileList
        const { fileList = [] } = this.data;
        fileList.push({ ...file, url: res.data });
        this.setData({ fileList });
        console.log(fileList)
      },
    });
  },
  deleteFile(e) {
    // 获取要删除的文件id
    const deletedId = e.detail.file.id;
    // 使用filter方法创建新数组（推荐不可变数据方式）
    const newFileList = this.data.fileList.filter(item => item.id !== deletedId);
    // 更新数据驱动视图
    this.setData({
      fileList: newFileList
    });
    // 如果需要，这里可以添加删除后的回调逻辑
    console.log('删除后的文件列表:', this.data.fileList);
  },
  handleListConfirm(e) {
    const selectedItems = e.detail.selectedItems[0];
    console.log('选中的项：', selectedItems);
    this.setData({
      'contractInfo.customerName': selectedItems.name,
      'contractInfo.customerid': selectedItems.id,
    })
  }
})